<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Stock Data Chart</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.2.2/echarts.min.js"></script>
</head>
<body>
<div id="main" style="width: 100%; height: 600px;"></div>
<input type="date" id="dateInput" placeholder="请输入日期">
<button id="searchBtn">查询</button>
<div id="result"></div>
<div id="dataContainer"></div>

<script>
// 初始化ECharts
var chart = echarts.init(document.getElementById('main'));

// 初始化数据为空数组
var stockData = [];

// 获取数据
function fetchData() {
    fetch("/stock_data")
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        // 更新全局的 stockData
        stockData = data;

        // 更新页面上的数据展示
<!--        renderStockData();-->

        // 处理数据并设置图表
        const dates = stockData.map(item => item.date);
        const closePrices = stockData.map(item => item.close);
        const openPrices = stockData.map(item => item.open);
        const lowPrices = stockData.map(item => item.low);
        const highPrices = stockData.map(item => item.high);
        const volumes = stockData.map(item => item.volume);

        const option = {
            title: {
                text: 'Stock Data Chart'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['Close Price', 'Open Price', 'Low Price', 'High Price', 'Volume']
            },
            xAxis: {
                type: 'category',
                data: dates,
                axisLabel: {
                    formatter: function (value) {
                        return new Date(value).toISOString().split('T')[0];
                    }
                }
            },
            yAxis: [
                {
                    type: 'value',
                    name: 'Price',
                    position: 'left'
                },
                {
                    type: 'value',
                    name: 'Volume',
                    position: 'right'
                }
            ],
            series: [
                {
                    name: 'Close Price',
                    type: 'line',
                    data: closePrices
                },
                {
                    name: 'Open Price',
                    type: 'line',
                    data: openPrices
                },
                {
                    name: 'Low Price',
                    type: 'line',
                    data: lowPrices
                },
                {
                    name: 'High Price',
                    type: 'line',
                    data: highPrices
                },
                {
                    name: 'Volume',
                    type: 'bar',
                    yAxisIndex: 1,
                    data: volumes
                }
            ]
        };

        chart.setOption(option);
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });
}

// 初次加载页面时获取数据
fetchData();

// 渲染股票数据到页面上
function renderStockData() {
    const dataContainer = document.getElementById('dataContainer');
    dataContainer.innerHTML = ''; // 清空容器

    const table = document.createElement('table');
    table.innerHTML = `
        <thead>
            <tr>
                <th>Date</th>
                <th>Open</th>
                <th>Close</th>
                <th>High</th>
                <th>Low</th>
                <th>Volume</th>
            </tr>
        </thead>
        <tbody>
            ${stockData.map(item => `
                <tr>
                    <td>${item.date}</td>
                    <td>${item.open}</td>
                    <td>${item.close}</td>
                    <td>${item.high}</td>
                    <td>${item.low}</td>
                    <td>${item.volume}</td>
                </tr>
            `).join('')}
        </tbody>
    `;

    dataContainer.appendChild(table);
}

// 查询功能
document.getElementById('searchBtn').addEventListener('click', function() {
    const date = document.getElementById('dateInput').value;
    if (date) {

        const selectedData = stockData.find(item => item.date.split('T')[0] === date);
        if (selectedData) {
            const resultDiv = document.getElementById('result');
            // 格式化并显示查询结果
            resultDiv.innerHTML = `
                <div style="border: 1px solid #ccc; padding: 10px; margin-top: 10px;">
                    <h3>查询结果</h3>
                    <ul style="list-style-type: none; padding: 0;">
                        <li><strong>ID:</strong> ${selectedData.id}</li>
                        <li><strong>日期:</strong> ${selectedData.date.split('T')[0]}</li>
                        <li><strong>开盘价:</strong> ${selectedData.open}</li>
                        <li><strong>收盘价:</strong> ${selectedData.close}</li>
                        <li><strong>最高价:</strong> ${selectedData.high}</li>
                        <li><strong>最低价:</strong> ${selectedData.low}</li>
                        <li><strong>成交量:</strong> ${selectedData.volume}</li>
                        <li><strong>交易金额:</strong> ${selectedData.transactionAmount}</li>
                        <li><strong>涨跌额:</strong> ${selectedData.changeAmount}</li>
                        <li><strong>涨跌幅:</strong> ${selectedData.changePercentage}%</li>
                        <li><strong>振幅:</strong> ${selectedData.amplitude}</li>
                        <li><strong>换手率:</strong> ${selectedData.turnoverRate}</li>
                    </ul>
                </div>
            `;

<!--            resultDiv.innerHTML = `查询结果：${JSON.stringify(selectedData)}`;-->
        } else {
            const resultDiv = document.getElementById('result');
            resultDiv.innerHTML = `找不到日期为 ${date} 的数据`;
        }
    } else {
        alert('请输入日期');
    }
});
</script>
</body>
</html>
